import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { formatMessage, FormattedMessage } from 'umi-plugin-react/locale';
import {
  Form,
  Input,
  DatePicker,
  Select,
  Button,
  Card,
  InputNumber,
  Radio,
  Icon,
  Tooltip,
  Upload,
} from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import styles from '../Less/form.less';
import 'braft-editor/dist/index.css';
import BraftEditor from 'braft-editor';
import { ContentUtils } from 'braft-utils';
import { ImageUtils } from 'braft-finder';
import { router } from 'umi';

const FormItem = Form.Item;
const { Option } = Select;
const { RangePicker } = DatePicker;
const { TextArea } = Input;

@connect(({ loading }) => ({
  submitting: loading.effects['doc/addDoc'],
}))
@Form.create()
class BasicForms extends PureComponent {
  constructor(props, context) {
    super(props, context);
    this.state = {
      // 创建一个空的editorState作为初始值
      editorState: BraftEditor.createEditorState('<div></div>'), // 设置编辑器初始内容
      outputHTML: '<div></div>',
    };
  }

  componentDidMount() {
    this.isLivinig = true;
    // 3秒后更改编辑器内容
    setTimeout(this.setEditorContentAsync, 3000);
  }

  componentWillUnmount() {
    this.isLivinig = false;
  }

  handleChange = editorState => {
    this.setState({
      editorState: editorState,
    });
  };

  setEditorContentAsync = () => {
    this.isLivinig &&
      this.setState({
        editorState: BraftEditor.createEditorState('<p>你好，<b>世界!</b><p>'),
      });
  };
  uploadHandler = param => {
    let _this = this;
    const { dispatch } = this.props;
    const formData = new FormData();

    if (!param.file) {
      return false;
    }
    formData.append('picture', param.file);
    dispatch({
      type: 'doc/uploadDocPhoto',
      payload: formData,
      callback: url => {
        // 使用ContentUtils.insertMedias来插入媒体到editorState
        const editorState = ContentUtils.insertMedias(this.state.editorState, [
          {
            type: 'IMAGE',
            url: 'http://wx3.sinaimg.cn/mw690/473fa942ly1g4t7xv62uuj211n0u0k0d.jpg',
          },
        ]);
        // 更新插入媒体后的editorState
        _this.setState({ editorState });
      },
    });
  };

  handleSubmit = e => {
    const { dispatch, form } = this.props;
    e.preventDefault();
    console.log(this.state.outputHTML);
    form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        values.content = this.state.editorState.toHTML();
        dispatch({
          type: 'doc/addDoc',
          payload: values,
          callback() {
            router.push('/doclist/table-list');
          },
        });
      }
    });
  };

  render() {
    const {
      form: { getFieldDecorator },
      submitting,
    } = this.props;
    const { editorState } = this.state;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 10 },
      },
    };

    const submitFormLayout = {
      wrapperCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 10, offset: 7 },
      },
    };
    const controls = [
      'bold',
      'italic',
      'underline',
      'text-color',
      'separator',
      'link',
      'separator',
    ];
    const extendControls = [
      {
        key: 'antd-uploader',
        type: 'component',
        component: (
          <Upload accept="image/*" showUploadList={false} customRequest={this.uploadHandler}>
            {/* 这里的按钮最好加上type="button"，以避免在表单容器中触发表单提交，用Antd的Button组件则无需如此 */}
            <button
              type="button"
              className="control-item button upload-button"
              data-title="插入图片"
            >
              <Icon type="picture" theme="filled" />
            </button>
          </Upload>
        ),
      },
    ];
    const myUploadFn = param => {
      const serverURL = '/lgjserve/singleupload';
      const xhr = new XMLHttpRequest();
      const fd = new FormData();

      const successFn = response => {
        // 假设服务端直接返回文件上传后的地址
        // 上传成功后调用param.success并传入上传后的文件地址
        let data = JSON.parse(xhr.responseText);
        console.log(data);
        param.success({
          url: data.data,
        });
      };

      const progressFn = event => {
        // 上传进度发生变化时调用param.progress
        param.progress((event.loaded / event.total) * 100);
      };

      const errorFn = response => {
        // 上传发生错误时调用param.error
        param.error({
          msg: 'unable to upload.',
        });
      };

      xhr.upload.addEventListener('progress', progressFn, false);
      xhr.addEventListener('load', successFn, false);
      xhr.addEventListener('error', errorFn, false);
      xhr.addEventListener('abort', errorFn, false);

      fd.append('picture', param.file);
      xhr.open('POST', serverURL, true);
      xhr.send(fd);
    };

    return (
      <PageHeaderWrapper title="添加帮助文档" content="添加帮助文档">
        <Card bordered={false}>
          <Form onSubmit={this.handleSubmit} hideRequiredMark style={{ marginTop: 8 }}>
            <FormItem {...formItemLayout} label="标题">
              {getFieldDecorator('title', {
                rules: [{ required: true, message: '请输入标题' }],
              })(<Input placeholder="输入标题" />)}
            </FormItem>
            <FormItem {...formItemLayout} label="类别">
              {getFieldDecorator('parent_id', {
                rules: [{ required: true, message: '请选择类别' }],
                initialValue: 1,
              })(
                <Radio.Group>
                  <Radio value={1}>用户</Radio>
                  <Radio value={2}>商户</Radio>
                </Radio.Group>
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="内容">
              <BraftEditor
                value={editorState}
                className={styles.myEditor}
                placeholder="请输入内容"
                onChange={this.handleChange}
                media={{
                  uploadFn: myUploadFn,
                }}
              />
            </FormItem>
            <FormItem {...submitFormLayout} style={{ marginTop: 32 }}>
              <Button type="primary" htmlType="submit" loading={submitting}>
                <FormattedMessage id="form.submit" />
              </Button>
              <Button style={{ marginLeft: 8 }}>
                <FormattedMessage id="form.reset" />
              </Button>
            </FormItem>
          </Form>
        </Card>
      </PageHeaderWrapper>
    );
  }
}

export default BasicForms;
